package com.group15.phms;

import java.util.ArrayList;
import java.util.List;

import com.group15.phms.AddNewDialogFragment.AddNewDialogListener;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TimePicker;
import android.support.v4.app.NavUtils;

public class AddMedication extends ListActivity implements AddNewDialogListener{
	SharedPreferences logins;
	DatabaseHelper db;
	ListView doseView;
	List<String> doseStrings = new ArrayList<String>();
	List<Dose> doseList = new ArrayList<Dose>();
	ArrayAdapter<String> adapter;
	String currentUser;
	EditText n,g;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_medication);
		// Show the Up button in the action bar.
		setupActionBar();
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());
		
		findViewById(R.id.okButton).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						submit();
					}
				});
		findViewById(R.id.cancelButton).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						cancel();
					}
				});
		n=(EditText)findViewById(R.id.addMedName);
		n.requestFocus();
		g=(EditText)findViewById(R.id.addGenName);
		doseStrings.add("<Tap to add new dose>");
		adapter = new ArrayAdapter<String>(  this, 
                android.R.layout.simple_list_item_1,
                doseStrings
            );
		ListView doseView = (ListView)findViewById(android.R.id.list);
		doseView.setAdapter(adapter);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.add_medication, menu);
		return true;
	}

	Intent intent;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		case R.id.action_search:
			intent = new Intent(this, Search.class);
	    	startActivity(intent);
			return true;
		case R.id.addbutton:
			createNew();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        if(position==l.getCount()-1)
        {
	        createNew();
        }	
    }
	
	public void createNew()
	{
		DialogFragment f = new AddNewDialogFragment();
        f.show(getFragmentManager(), "AddDoseDialogFragment");
	}
	
	public void submit()
	{
		MedicationMonitor mm = new MedicationMonitor();
		Medication m = new Medication(n.getText().toString(),g.getText().toString()); 
		db.addMedication(m, currentUser);
		for (Dose d: doseList)
		{
			db.addDose(d, currentUser, g.getText().toString());
			mm.createNotification(m, d, this);
		}
		finish();
	}
	public void cancel()
	{
		finish();
	}

	@Override
	public void onPositiveClick(View view) {
		EditText e = (EditText)view.findViewById(R.id.amount);
 	   	String amount = (e.getText().toString());
 	   	e = (EditText)view.findViewById(R.id.type);
 	    String type = (e.getText().toString());
 	    TimePicker t = (TimePicker)view.findViewById(R.id.timePicker1);
 	    Dose d = new Dose(amount,type,t.getCurrentHour(),t.getCurrentMinute());
 	    doseList.add(d);
 	    doseStrings.add(doseStrings.size()-1, d.toString());
 	    adapter.notifyDataSetChanged();
 	    
	}
}

class AddNewDialogFragment extends DialogFragment {
	String callingActivity;
	
	/* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface AddNewDialogListener {
        public void onPositiveClick(View v);
    }
    
    // Use this instance of the interface to deliver action events
    AddNewDialogListener mListener;
    
    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callingActivity = (activity.getClass().getSimpleName());
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (AddNewDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement AddNewDialogListener");
        }
    }
	
    
    
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final View view;
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		System.out.println(callingActivity);
	    // Get the layout inflater
	    LayoutInflater inflater = getActivity().getLayoutInflater();
	    if(callingActivity.equals("AddMedication") || callingActivity.equals("MedicationInfo"))
	    	view = inflater.inflate(R.layout.dialog_add_dose, null);
	    else if(callingActivity.equals("DoctorInfo"))
	    	view = inflater.inflate(R.layout.dialog_add_doctor, null);
	    else if(callingActivity.equals("ContactInfo"))
	    	view = inflater.inflate(R.layout.dialog_add_contact, null);
	    else
	    	view = null;	
	    
	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setView(view)
	    // Add action buttons
	           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	            	   mListener.onPositiveClick(view);
	               }
	           })
	           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   AddNewDialogFragment.this.getDialog().cancel();
	               }
	           });
	    // Create the AlertDialog object and return it
	    return builder.create();
	}
}
